//接收前端传来的token
const basicAuth = require('basic-auth');
const jwt = require('jsonwebtoken');
const {security} = require('./tokentime');
const result = require('@/utils/handle');
class Auth{
    get m(){
        return async(ctx,next) => {
            const token = basicAuth(ctx.req)
            console.log('token',token);
            if(!token||!token.name) {
                throw new result('未登录，没有访问权限',401)
            }
            try {
                var authcode = jwt.verify(token.name,security.secretKey)
                console.log('authcode',authcode);
                
            } catch (error) {
                if(error.name === 'TokenExpiredError'){
                    throw new result('登录态过期，请重新登陆',401)
                }
                throw new result('没有访问权限',401)
            }
            
            ctx.auth = {
                uid:authcode.uid
            }
            await next()
        }
    }
}

module.exports = {
    Auth
}